#  Copyright (c) 2023. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
#  Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
#  Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
#  Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
#  Vestibulum commodo. Ut rhoncus gravida arcu.

# coding:utf8
import json

from log import logger

from project import IP
from typing import Union

OLD_SIP_DEFAULT_IP = "192.168.1.11"


class IpSelect:
    def __init__(self, ip_start_end_tuple: Union[tuple, str]):
        
        if isinstance(ip_start_end_tuple, str):
            ip_start_end_tuple = [ip_start_end_tuple, ip_start_end_tuple]
        elif not isinstance(ip_start_end_tuple, (list, tuple)):
            raise ValueError("ip range is not list or tuple")
        self.ipstr_list = IP.get_range_ipstr_list(*ip_start_end_tuple)
        
        
    def funcname(self):
        """
        IP列表中的第一个IP都要创建一个线程, 不断的ping
        如果有在线的开启handlesip,并
            1 暂停ping此ip, 线程不断
            2 等待handlesip结束
                再开启ping原始IP
        
        
                
        """
        pass


path = "config\\cookies.txt"


class Cookies:
    def __init__(self, driver, path = path):
        self.path = path
        self.driver = driver
        
    
    def save(self):
        cookies = self.driver.get_cookies()  # 获取cookies
        logger.debug("获取cookies {}".format(cookies not in [None, "", [], {}]))
        con = json.dumps(cookies, indent=4, ensure_ascii=False)
        with open(self.path, 'w', encoding='utf8') as f:
            f.write(con)
            logger.debug("write cookies success")
    
    def set_cookies(self):
        try:
            with open(self.path, 'r', encoding='utf8') as f:
                logger.debug("reading cookies")
                cookies = f.read()
                cook_list = json.loads(cookies)
                if not cookies:
                    return False
                for c in cook_list:
                    self.driver.add_cookie(c)
                self.driver.refresh()  # 刷新后页面显示已登陆
                return True
        except:
            return False